/**
 * tinymce 工具函数
 * 无状态函数、可移植
 */
export const uuid = (prefix: string): string => {
  return `${prefix}_${Date.now() + Math.floor(Math.random() * 1000000)}`;
};

export const getTinymce = (): any => {
  const root = typeof window !== 'undefined' ? window : global;
  return root && 'tinymce' in root ? root.tinymce : null;
};

export function getContent(editor: any): any {
  if (!editor) return '';
  return editor.getContent();
}

export function setContent(val: any, editor: any) {
  if (!editor) return;
  editor.setContent(val);
}

export function resetContent(val: any, editor: any) {
  if (!editor) return;
  // eslint-disable-next-line consistent-return
  if (editor.resetContent) return editor.resetContent(val);
  // 若无 reset fun，则手动 reset
  editor.setContent(val);
  editor.setDirty(false); // 恢复初始状态
  editor.undoManager.clear();
}

export function setModeDisabled(editor: any, disabled = true) {
  if (!editor) return;
  editor.mode.set(disabled ? 'readonly' : 'design');
}
